<template>
  <div>
    <el-dialog
        title="设置服务查询"
        v-el-drag-dialog
        :visible="config.show===true"
        :close-on-click-modal="false"
        :before-close="handleClose"
    >
      <el-form ref="form" label-width="120px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="数据服务地址：">
              <el-input class="input" placeHolder="输入数据服务地址" v-model="dataUrl"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">&ensp;</el-col>
          <el-col :span="2">
            <el-button type="primary" @click="loadDatasourcesFromUrl">读取</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="数据源：">
              <el-select style="width: 100%;" value-key="value" v-model="datasourceName" filterable clearable
                         @change="handleDatasourceChange">
                <el-option v-for="datasource in configData.datasourceNames"
                           :key="datasource.value"
                           :label="datasource.name"
                           :value="datasource.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="数据集：">
              <el-select style="width: 100%;" value-key="value" v-model="datasetName" filterable clearable
                         @change="handleDatasetChange">
                <el-option v-for="dataset in configData.datasetNames"
                           :key="dataset.value"
                           :label="dataset.name"
                           :value="dataset.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="分析服务地址：">
              <el-input class="input" placeHolder="输入分析服务地址" v-model="analysisUrl"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">字段配置</el-divider>
        <el-row>
          <el-col :span="23">
            <el-table
                ref="fieldsTable"
                :data="configData.fieldData.slice((pageData.currentPage-1)*pageData.pageSize,pageData.currentPage*pageData.pageSize)"
                height="320"
                style="width: 100%;"
                row-key="LAY_TABLE_INDEX"
                border
            >
              <el-table-column
                  type="index"
                  :index="fieldIndexComputed"
                  label="序号"
                  align="center"
              ></el-table-column>
              <el-table-column
                  prop="f_field"
                  label="字段名"
                  align="center"
              ></el-table-column>
              <el-table-column
                  prop="f_fieldcn"
                  label="中文名"
                  align="center"
              >
                <template slot-scope="scope">
                  <el-input
                      type="text"
                      style="width:100%;height:100%; border:0px;"
                      v-model="scope.row.f_fieldcn"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                  prop="f_unit"
                  label="单位"
                  align="center"
              >
                <template slot-scope="scope">
                  <el-input type="text" style="width:100%;height:100%;" v-model="scope.row.f_unit"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                  prop="f_isvisible"
                  label="是否可见"
                  align="center"
              >
                <template slot-scope="scope">
                  <el-switch type="text" :value="scope.row.f_isvisible==0?false:true" @change="fieldIsVisible($event,scope.row)"></el-switch>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handlePageSizeChange"
                @current-change="handlePageCurrentChange"
                :current-page="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size="pageData.pageSize"
                layout="total,sizes,prev,pager,next,jumper"
                :total="configData.fieldData.length"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handleOk">确定</el-button>
				<el-button @click="handleClose">取消</el-button>
			</span>
    </el-dialog>
  </div>
</template>

<script>
import * as gcf from "@/utils/Global/GlobalCommonFunction";
import { updateCatalogQuery,queryCatalogQuery } from '@/api/resource/resourceCatalog';
import elDragDialog from '@/directive/el-dragDialog/'

export default {
  name: "editServiceQuery",
  data() {
    return {
      dataUrl: "",
      datasourceName: "",
      datasetName: "",
      analysisUrl: "",
      fieldsTable: null,
      configData: {
        serviceQueryData: null,
        datasourceNames: [],
        datasetNames: [],
        fieldData: [],
        defaultFieldList: ['SMID', 'SMX', 'SMY', 'SMSDRIW', 'SMSDRIN', 'SMSDRIE', 'SMSDRIS', 'SMUSERID', 'SMAREA', 'SMLENGTH', 'SMTOPOERROR',
          'SMPERIMETER', 'SMGEOMETRYSIZE', 'SMGEOPOSITION', 'SMGEOTYPE', 'SMLIBTILEID', 'SMGEOMETRY']
      },
      pageData: {
        pageSizes: [10, 20, 30],
        pageSize: 10,
        currentPage: 1
      }
    }
  },
  directives: {//到这里了，看看自定义组件怎么个用法
    elDragDialog,
  },
  props: {
    config: {
      type: Object,
      default() {
        return {
          show: false,
        }
      }
    },
    param: {
      type: Object,
      default() {
        return {}
      }
    },
    form: {
      type: Object,
      default() {
        return {
          serviceId: "",
        }
      }
    },
  },
  mounted() {
    this.queryServiceQueryData(this.form.serviceId);
  },
  methods: {
    fieldIndexComputed(index){
      let that = this;
      return index + 1 + (that.pageData.currentPage-1)*that.pageData.pageSize;
    },
    fieldIsVisible(value,row){
      row.f_isvisible = value==true?1:0;
    },
    /**
     * 关闭弹窗
     */
    handleClose() {
      let that = this;
      that.config.show = false;
    },
    /**
     * 改变数据集事件
     * @param dataset
     */
    handleDatasetChange(dataset) {
      let that = this;
      that.datasetName = dataset;
      if (gcf.IsNotNullStr(that.datasetName) && gcf.IsNotNullStr(that.datasourceName) && gcf.IsNotNullStr(that.dataUrl)) {
        let readFields = new ol.supermap.FieldService(that.dataUrl).getFields(new SuperMap.FieldParameters({
          datasource: that.datasourceName,
          dataset: that.datasetName
        }), function (fieldResult) {
          that.configData.fieldData = [];
          let fields = fieldResult.result.fieldNames;
          for (let i in fields) {
            let field = fields[i];
            let isVisible = 1;
            if (that.configData.defaultFieldList.indexOf(field.toUpperCase()) >= 0) {
              isVisible = 0;
            }
            that.configData.fieldData.push({
              "LAY_TABLE_INDEX": parseInt(i) + 1
              , "f_field": field
              , "f_fieldcn": field
              , "f_unit": null
              , "f_isvisible": isVisible
            });
          }
        });
      }
    },
    /**
     * 改变数据源事件
     * @param datasource
     */
    handleDatasourceChange(datasource) {
      let that = this;
      that.datasourceName = datasource;
      if (gcf.IsNotNullStr(that.datasourceName) && gcf.IsNotNullStr(that.dataUrl)) {
        let readDataset = new ol.supermap.DatasetService(that.dataUrl).getDatasets(that.datasourceName, function (datasetResult) {
          let datasetNames = datasetResult.result.datasetNames;
          that.configData.datasetNames = [];
          for (let i in datasetNames) {
            let datasetName = datasetNames[i];
            that.configData.datasetNames.push({"name": datasetName, "value": datasetName});
          }
        });
      }
    },
    /**
     * 页码点击事件
     * @param size
     */
    handlePageSizeChange(size) {
      this.pageData.pageSize = size;
    },
    /**
     * 跳转页面事件
     * @param currentPage
     */
    handlePageCurrentChange(currentPage) {
      this.pageData.currentPage = currentPage;
    },
    /**
     * 确定事件
     */
    handleOk() {
      let that = this;
      let params={
        "serviceId": that.form.serviceId,
        "url": that.dataUrl,
        "datasource": that.datasourceName,
        "dataset": that.datasetName,
        "analysisUrl": that.analysisUrl,
        "fieldConfig": JSON.stringify(that.configData.fieldData)
      };
      updateCatalogQuery(params).then((res) => {
        if (res.code==200) {
          that.$message({
            message: '查询配置更新：'+res.msg+'！',
            type: 'success'
          });
          that.config.show = false;
        }else{
          that.$message.error('查询配置更新失败！'+res.code+":::"+res.msg);
        }
      }).catch(resp => {
        console.log('queryCatalogQuery', resp.status + "," + resp.statusText);
      });

    },
    /**
     * 读取数据服务地址，加载数据源
     */
    loadDatasourcesFromUrl() {
      let that = this;
      if (gcf.IsNotNullStr(that.dataUrl)) {
        let readDatasource = new ol.supermap.DatasourceService(that.dataUrl).getDatasources(function (datasourceResult) {
          let datasourceNames = datasourceResult.result.datasourceNames;
          that.configData.datasourceNames = [];
          for (let i in datasourceNames) {
            let datasourceName = datasourceNames[i];
            that.configData.datasourceNames.push({"name": datasourceName, "value": datasourceName});
          }
        });
      }
    },
    /**
     * 查询数据服务配置
     * @serviceId serviceId
     */
    queryServiceQueryData(serviceId) {
      let that = this;
      queryCatalogQuery(serviceId).then((res) => {
        if (res.data.queryData.length > 0) {
          let obj = res.data.queryData[0];
          that.dataUrl = obj.url;
          that.analysisUrl = obj.analysisUrl;
          that.configData.datasourceNames = obj.datasource;
          that.configData.datasetNames = obj.dataset;
          that.datasourceName = obj.datasource;
          that.datasetName = obj.dataset;
          that.configData.fieldData = JSON.parse(obj.fieldConfig);
        }
      }).catch(resp => {
        console.log('queryCatalogQuery', resp.status + "," + resp.statusText);
      });
    },
  }
}
</script>

<style scoped>
::v-deep .el-divider--horizontal {
  margin: 10px 0px;
}

::v-deep .el-form-item {
  margin-bottom: 10px;
}
</style>
